package pers.qianyu.month_202011.date_20201116;

import pers.qianyu.util.*;

import java.util.*;

/**
 * 567. 字符串的排列
 * https://leetcode-cn.com/problems/permutation-in-string/
 *
 * @author mizzle rain
 * @date 2020年11月16日13:02:00
 */
public class CheckInclusion2 {
    /**
     * 维护一个不可变的滑动窗口
     */
    public boolean checkInclusion(String s1, String s2) {
        int left = 0, right = s1.length() - 1;
        HashMap<Character, Integer> need = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        while (right < s2.length()) {
            ArrayUtil.printArr(s2.toCharArray(), left, right);
            String part = s2.substring(left, right + 1);
            if (isValid(part, need)) {
                return true;
            }
            right++;
            left++;
        }
        return false;
    }

    private boolean isValid(String part, HashMap<Character, Integer> need) {
        int valid = 0;
        HashMap<Character, Integer> window = new HashMap<>();
        for (int i = 0; i < part.length(); i++) {
            char c = part.charAt(i);
            window.put(c, window.getOrDefault(c, 0) + 1);
            if (window.get(c).equals(need.get(c))) {
                valid++;
            }
        }
        return valid == need.size();
    }

    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "eidbaooo";
        ArrayUtil.printIndex(s2.length());
        CheckInclusion2 c = new CheckInclusion2();
        boolean result = c.checkInclusion(s1, s2);
        System.out.println("result = " + result);
    }
}
